<?php
namespace control;
/*
*暂估调整单类
*/

class purchaseEstimationOrderClass extends adIndexClass
{
	private const page    = 'purchaseEstimationOrder';
	private const table   = 'purchase_esti_order';
	private const tableMx = 'purchase_esti_order_detail';
	private const title   = '暂估调整单';

    /**
     * 字段初始化
     */
    public function fieldInit($fun): array
    {
        switch ($fun) {
            default:
                $tr = [
                    'orderNo'          => [
                        'name'  => '单据编号',
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'supplier' => [
                        'name'  => "供应商",
                        'width' => 270,
                    ],
                    'moneyWithOutTax'  => [
                        'name'  => '总未税金额差额(' . static::$unit . ')',
                        'width' => 200,
                    ],
                    'taxMoney'         => [
                        'name'  => '总税额差额(' . static::$unit . ')',
                        'width' => 200,
                    ],
                    'money'          => [
                        'name'  => '总价税合计差额(' . static::$unit . ')',
                        'width' => 200,
                    ],
                    'recordDate'          => [
                        'name'  => '单据日期',
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'state'          => [
                        'name'  => '状态',
                        'width' => 200,
                    ]
                ];
        }
        return $tr;
    }

    /*列表页-查询条件*/
    public function homeOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->tableShow([
            [
                [
                    "单据编号" => text(array("name" => "orderNo")),
                    '供应商' => supplierClass::supplierSelect(array('title' => '')),
                    "单据日期" => text(array("name" => "createTime", 'laydate' => ['type' => 'date', 'range' => '~'])),
                ],
                [
                    "状态" => select(["name" => "state", 'option' => ['草稿', '待确认', '已确认']]),
                ]
            ]
        ],1);
        //返回
        if (!$isAsync) {
            return $html;
        } else {
            return json_encode(['html' => $html], 320);
        }
    }

	/*列表-查询条件*/
	public function home()
	{
        $html = $this->homeOptions(false);
        //控件
        $button = "";
        $url = root . "control/adIndex.html?cla=" . self::page;
        $isEdit = $this->power(self::page, "edit");
        if ($isEdit) {
            $button .= "<span onclick=\"newIframe('" . self::title . "详情','" . $url . "&fun=edit')\" class='spanButton'>新增</span>\n";
        }
        if ($this->power(self::page, "del")) {
            $button .= "<span class='spanButton' onclick=\"layer('{$this->get('cla')}', 'operate', {'act': 'del'})\">删除</span>\n";
        }
        if ($this->power(self::page, "print")) {
            $button .= " <span onclick=\"batchPrint('" . $this->get('cla') . "')\" class='spanButton'>批量打印</span>\n";
        }
		//返回
		return $this->homeFun($this->search($html, layout: 'pop', toolButton: $button));
	}

	/*客户列表-查询结果*/
	public function homeSearch()
	{
		//like查询数组
		$like = array(
			"orderNo" => $this->post('orderNo'),//编号
		);
		//全等查询数组
		$equal = array(
			'coid'       => self::$coid,
			"state"      => $this->post('state'),
			"supplierId" => $this->post('supplierId'),
		);
		$and   = '';
		if ($this->post('createTime')) {
			$and .= self::timeComparison($this->post('createTime'), 'date', 'recordDate');
		}
        //排序
        $orderBy = $this->listSort(array(
            "search"  => $this->post('list_sort_key') ?: 'recordDate desc,orderNo',
            "sort" => $this->post('list_sort') ?: "desc",
            "array"   => array(),
        ));
		//获取查询结果
		$where = search(array("like" => $like, "=" => $equal)) . $and;
		$page  = $this->page(array("table" => self::table, "where" => $where, "order" => $orderBy['orderBy']));
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array(
            $this->checkAll("listForm", "listId")
        );
		//获取记录
		$url = root . "control/adIndex.html?cla=" . self::page;
		$isEdit = $this->power(self::page, "edit");
		foreach ($page['array'] as $array) {
			//列表控件
			$dominate = array(
				"box"    => array("name" => "listId", "value" => $array['id']),
				"edit"   => array("title" => "编辑", "click" => "newIframe('" . self::title . "详情','" . $url . "&fun=edit&id=" . $array['id'] . "')"),
				"detail" => array("title" => self::title . "详情", "click" => "newIframe('" . self::title . "详情','" . $url . "&fun=detail&id=" . $array['id'] . "')"),
				'print'  => array('title' => '打印', 'click' => "window.open('" . root . "control/adIndex.html?cla=" . self::page . "&fun=printPage&id={$array['id']}')"),
			);
			if ($array['state'] != '草稿' || !$isEdit) {
				unset($dominate['edit']);
			}
			$total    = find(array(
			    'table' => self::tableMx,
                'single' => "orderId = '$array[id]'",
                'field' => "ifnull(sum(taxMoney),0) as taxMoney,ifnull(sum(moneyWithOutTax),0) as moneyWithOutTax,ifnull(sum(money),0) as money"
            ));
			$preTotal = find(array(
			    'table' => 'purchase_get_order_detail',
                'single' => "id in (select sourceId from " . self::tableMx . " where orderId = '$array[id]')",
                'field' => "ifnull(sum(taxMoney),0) as taxMoney,ifnull(sum(moneyWithOutTax),0) as moneyWithOutTax,ifnull(sum(money),0) as money"
            ));
            $liButton[] = $this->dominate($dominate);
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    case "supplier":
                        $row[] = supplierClass::getName($array['supplierId']);
                        break;
                    case "moneyWithOutTax":
                        $row[] = self::formattingFigure($total['moneyWithOutTax'] - $preTotal['moneyWithOutTax']);
                        break;
                    case "taxMoney":
                        $row[] = self::formattingFigure($total['taxMoney'] - $preTotal['taxMoney']);
                        break;
                    case "money":
                        $row[] = self::formattingFigure($total['money'] - $preTotal['money']);
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
		}
        $total    = find(array(
            'table' => self::tableMx,
            'single' => "orderId in (select id from ".self::table." where 1=1 {$where})",
            'field' => "ifnull(sum(taxMoney),0) as taxMoney,ifnull(sum(moneyWithOutTax),0) as moneyWithOutTax,ifnull(sum(money),0) as money"
        ));
        $preTotal = find(array(
            'table' => 'purchase_get_order_detail',
            'single' => "id in (select sourceId from " . self::tableMx . " where orderId in (select id from ".self::table." where 1=1 {$where}))",
            'field' => "ifnull(sum(taxMoney),0) as taxMoney,ifnull(sum(moneyWithOutTax),0) as moneyWithOutTax,ifnull(sum(money),0) as money"
        ));
        $total    = [
            'moneyWithOutTax'      => self::formattingFigure($total['moneyWithOutTax'] - $preTotal['moneyWithOutTax']),
            'taxMoney'      => self::formattingFigure($total['taxMoney'] - $preTotal['taxMoney']),
            'money'      => self::formattingFigure($total['money'] - $preTotal['money']),
        ];
        //生成页面
        $li = $this->li(array(
            "body" => $body,
            "install" => $installSearch,
            "button" => array("html" => $liButton),
            "orderBySign" => $orderBy,
            "page" => $page['para'],
            "total"       => $total,
        ));
		//返回
		$json['html'] = "<form name='listForm'>" . $li . "</form>" . $page['button'] . clear;
		return json_encode($json, 320);
	}

    /**
     * 保存并提交
     * @return bool|string
     */
    public function saveAndCommit(): bool|string
    {
        $resultJson = $this->editEdit();
        $result = json_decode($resultJson,true);
        if ($result['warn'] == 2){
            unset($_SESSION['warn']);
            $resultJson = $this->commitEdit();
        }
        return $resultJson;
    }
	/**
	 * 编辑页
	 *
	 * @return string
	 */
	public function edit(): string
	{
		/****新增****/
		$id   = $this->get('id') ?: self::getId();
		$info = query(self::table, " id = '" . $id . "' ");

		$button[] = [
			"name"  => "保存为草稿",
			"type"  => "点击事件",
			"title" => "保存",
			'fun'   => "subForm('" . self::page . "EditForm','" . root . "control/adIndex.html?cla=" . self::page . "&fun=editEdit')",
		];
        $button[] = [
            'style' => 'li-btn-blue-bg',
            "name" => "保存并提交",
            "type" => "点击事件",
            "title" => "保存",
            'fun' => "subForm('" . self::page . "EditForm','" . root . "control/adIndex.html?cla=" . self::page . "&fun=saveAndCommit')"
        ];
		$tr[]   = ['', '物料编码', '物料名称', '规格型号', '单位', '数量', '原单价(' . static::$unit . ')', '原税率%', '调整后单价（' . static::$unit . '）', '调整后税率%', '调整后未税金额（' . static::$unit . '）', '调整后税额（' . static::$unit . '）', '调整后价税合计（' . static::$unit . '）', '未税金额差额（' . static::$unit . '）', '税额差额（' . static::$unit . '）', '价税合计差额（' . static::$unit . '）', '关联采购收货单'];
		$result = find(array('table' => self::tableMx, 'where' => "orderId = '$info[id]' order by list"));
        $totalArr = ['num'=>0,'total_row_money'=>0,'total_tax_money'=>0,'total_money'=>0,'diff_money'=>0,'diff_tax_money'=>0,'diff_money_with_tax'=>0];
		foreach ($result['array'] as $k=>$array) {
			$material    = query('material', " id = '$array[materialId]'");
			$targetMx                    = query("purchase_get_order_detail", "id = '$array[sourceId]'");
			$target                      = query('purchase_get_order', "id = '$targetMx[orderId]'");
			$targetMx['money']           = $targetMx['money'] ?: 0;
			$targetMx['taxMoney']        = $targetMx['taxMoney'] ?: 0;
			$targetMx['moneyWithOutTax'] = $targetMx['moneyWithOutTax'] ?: 0;
			$diffMoney                   = self::formattingFigure($array['moneyWithOutTax'] - $targetMx['moneyWithOutTax']);
			$diffTaxMoney                = self::formattingFigure($array['taxMoney'] - $targetMx['taxMoney']);
			$diffMoneyWithTax            = self::formattingFigure($array['money'] - $targetMx['money']);
			$tr[] = [
                componentClass::tablePperation($k+1,"delTableRow(this);calculateTotal()").
                hidden(array('name' => 'mxId[]', 'value' => $array['id'])) .
				hidden(array('name' => 'materialId[]', 'value' => $array['materialId'])) .
				hidden(array('name' => 'sourceId[]', 'value' => $array['sourceId'])) .
				"<span class='pre_money hidden'>{$targetMx['moneyWithOutTax']}</span>" .
				"<span class='pre_tax_money hidden'>{$targetMx['taxMoney']}</span>" .
				"<span class='pre_money_with_tax hidden'>{$targetMx['money']}</span>",
				$material['code'],
				$material['name'],
				$material['model'],
				$targetMx['unit'],
				"<span class='num'>" . self::lostZero($array['num'], 'numPrecision') . "</span>",
				$targetMx['price'],
				($targetMx['rate'] * 100) . '%',
				text(array('name' => 'price[]', 'other' => self::digitalFiltering('pricePrecision'), 'blur' => 'countMoney', 'value' => self::lostZero($array['price'], 'pricePrecision'))),
				select(array('name' => 'rate[]', 'change' => 'countMoney', 'title' => '税率', 'option' => explode('，', para('taxRate')), 'value' => $array['rate'] * 100)),
				"<span class='rowMoney'>" . self::lostZero($array['moneyWithOutTax']) . "</span>",
				"<span class='taxMoney'>" . self::lostZero($array['taxMoney']) . "</span>",
				"<span class='moneyWithTax'>" . self::lostZero($array['money']) . "</span>",
				"<span class='diff_money'>{$diffMoney}</span>",
				"<span class='diff_tax_money'>{$diffTaxMoney}</span>",
				"<span class='diff_money_with_tax'>{$diffMoneyWithTax}</span>",
				$target['orderNo'] ?? '',
			];
            $totalArr['num'] += $array['num'];
            $totalArr['total_row_money'] += $array['moneyWithOutTax'];
            $totalArr['total_tax_money'] += $array['taxMoney'];
            $totalArr['total_money'] += $array['money'];
            $totalArr['diff_money'] += $diffMoney;
            $totalArr['diff_tax_money'] += $diffTaxMoney;
            $totalArr['diff_money_with_tax'] += $diffMoneyWithTax;
		}
        $total = [
            5 => "<span id='total_num'>".self::lostZero($totalArr['num'],'numPrecision')."</span>",
            10 => "<span id='total_row_money'>".self::lostZero($totalArr['total_row_money'])."</span>",
            11 => "<span id='total_tax_money'>".self::lostZero($totalArr['total_tax_money'])."</span>",
            12 => "<span id='total_money'>".self::lostZero($totalArr['total_money'])."</span>",
            13 => "<span id='diff_money'>".self::lostZero($totalArr['diff_money'])."</span>",
            14 => "<span id='diff_tax_money'>".self::lostZero($totalArr['diff_tax_money'])."</span>",
            15 => "<span id='diff_money_with_tax'>".self::lostZero($totalArr['diff_money_with_tax'])."</span>",
        ];
		$checked = $info['isTax'] ? 'checked' : '';
		$list    = $this->listTable(array('tr' => $tr, 'end' => true, 'total' => $total));
        $mxButton   = <<<efo
                <span class="smallButton" onclick="chooseOrder()">关联采购收货单</span>
                <span style="margin-left: 20px;">
                    <label class='checkbox'><input name='isTax' onclick="taxChange(this)" type='checkbox' $checked value='1'><span></span>&nbsp;含税</label>
                </span>
efo;

		//表单
        $data['button'] = $this->tableShowButton($button);
        $body = $this->edit4([
            '基本信息' => [
                [
                    must . "供应商："   =>
                        supplierClass::supplierSelect(array('value'=>$info['supplierId'],'param'=>"{type:'启用'}",'change'=>"emptyList()")),
                    //selectMultiple(["name" => "supplierId", "value" => $info['supplierId'], 'where' => "coid = '" . self::$coid . "' and state = '启用'", 'table' => "supplier", 'sqlId' => 'id', 'sqlField' => 'name', 'title' => '请选择']),
                    must . "单据日期：" => text(["name" => "recordDate", 'class' => 'text', 'laydate' => [], "value" => $info['recordDate'] ?: $this->date]),
                ],
                [
                    "备注："            => textarea(["name" => "text", 'class' => 'text', "value" => $info['text']]),
                ],
            ]
        ]);
        $body .= $this->editList([
            'id' => 'materialTable',
            'title' => '明细',
            'button' => $mxButton,
            'html' => $list,
        ]);
        $body .= $this->editBlock([
            '附件' => fileUploadClass::addFileComponent($id, '暂估调整单', self::page, self::page . 'EditForm')
        ]);
		$data['html'] = $this->pageEdit([
			"html"  => $body,
			'hidden' => hidden(['name' => 'id', 'value' => $id]),
		]);
		$data['html'] .= <<<efo
<script>
function chooseOrder(){
    let supplierId = $("[name='supplierId']").val();
    if (!supplierId){
        msg('请先选择供应商','error')
        return false;
    }
    layer('{$this->get('cla')}','addSendOrder',$('form[name=purchaseEstimationOrderEditForm]').serialize())
}
function addRow(){
    $.post(root+'control/adIndex.html?cla={$this->get('cla')}&fun=addSendOrderEdit',$("form[name='saleSendOrderForm']").serialize(),function(res) {
         $("#materialTable tbody").append(res.html);
         resetNumber($("#materialTable"))
    },'json');
}
//通过单价计算金额，税额等
function countMoney(e){
    let trObj = $(e).parent().parent();
    countProcess(trObj)
}
//切换含税不含税复选框
function taxChange(e){
    $("#materialTable tbody tr").each(function() {
       countProcess($(this))
    })
}
function countProcess(trObj){
    let price = trObj.find("[name='price[]']").val();
    let num = Number(trObj.find(".num").html());
    let rate = trObj.find("[name='rate[]']").val();
    rate = Number(rate)/100;
    let money =0;
    let taxMoney,moneyWithTax;
    if($("[name='isTax']").is(":checked")){
       //含税单价
       taxMoney = (Number(price)*Number(num)/(1+rate)*rate).toFixed(amountPrecision);
       moneyWithTax = (Number(price)*Number(num)).toFixed(amountPrecision);
       money = moneyWithTax-taxMoney;
    }else{
       //未含税单价
        taxMoney = (Number(price)*Number(num)*rate).toFixed(amountPrecision);
        moneyWithTax = (Number(price)*Number(num)*(1+rate)).toFixed(amountPrecision);
          money = moneyWithTax-taxMoney;
    }
    trObj.find(".rowMoney").html(money.toFixed(amountPrecision))
    trObj.find(".taxMoney").html(taxMoney)
    trObj.find(".moneyWithTax").html(moneyWithTax);
    
    let preMoney = Number(trObj.find(".pre_money").html());
    let preTaxMoney = Number(trObj.find(".pre_tax_money").html());
    let preMoneyWithTax = Number(trObj.find(".pre_money_with_tax").html());
    trObj.find(".diff_money").html((money-preMoney).toFixed(amountPrecision));
    trObj.find(".diff_tax_money").html((taxMoney-preTaxMoney).toFixed(amountPrecision));
    trObj.find(".diff_money_with_tax").html((moneyWithTax-preMoneyWithTax).toFixed(amountPrecision));
    calculateTotal();
}
//计算总金额，总税额
function calculateTotal(table=''){
    table = table ? table : $('.editList')
    let rowMoney = 0,
    taxMoney = 0,
    money = 0,
    diffMoney = 0,
    diffTaxMoney = 0,
    diffMoneyWithTax = 0
    table.find(".rowMoney").each(function(index){
        if($(this).text()){
          rowMoney+=Number($(this).text());
        }
        var taxMoneyText = table.find(".taxMoney").eq(index).text()
        if(taxMoneyText){
            taxMoney+=Number(taxMoneyText);
        }
        var moneyValueText = table.find(".moneyWithTax").eq(index).text()
        if(moneyValueText){
            money+=Number(moneyValueText);
        }
        var diffMoneyText = table.find(".diff_money").eq(index).text()
        if(diffMoneyText){
            diffMoney+=Number(diffMoneyText);
        }
        var diffTaxMoneyText = table.find(".diff_tax_money").eq(index).text()
        if(diffTaxMoneyText){
            diffTaxMoney+=Number(diffTaxMoneyText);
        }
        var diffMoneyWithTaxText = table.find(".diff_money_with_tax").eq(index).text()
        if(diffMoneyWithTaxText){
            diffMoneyWithTax+=Number(diffMoneyWithTaxText);
        }
    })
    $("#total_row_money").text(rowMoney.toFixed(amountPrecision));
    $("#total_tax_money").text(taxMoney.toFixed(amountPrecision));
    $("#total_money").text(money.toFixed(amountPrecision));
    $("#diff_money").text(diffMoney.toFixed(amountPrecision));
    $("#diff_tax_money").text(diffTaxMoney.toFixed(amountPrecision));
    $("#diff_money_with_tax").text(diffMoneyWithTax.toFixed(amountPrecision));
}
//切换供应商清空选择明细
function emptyList(e){
    $("#materialTable tbody").empty()
}
</script>

efo;
		//返回
		return $this->tab($data);
	}

	public function editEdit()
	{
		$fileIdArr        = $this->post('fileId');
		$id               = $this->post('id') ?: self::getId();
		$mxIdArr          = $this->post('mxId') ?: [];
		$materialIdArr = $this->post('materialId');
		$sourceIdArr      = $this->post('sourceId');
		$priceArr         = $this->post('price');
		$taxRateArr       = $this->post('rate');
		$field            = [
			'text'       => $this->post('text'),
			'supplierId' => $this->post('supplierId'),
			'recordDate' => $this->post('recordDate'),
			'isTax'      => $this->post('isTax') ? 1 : 0,
		];
		$where = " id = '$id' ";
		$info  = query(self::table, $where);
		//判断
		if (!$this->power(self::page, "edit")) {
			$json['warn'] = "你没有编辑" . self::title . "的权限";
		} elseif (!empty($info['id']) && $info['state'] == '已确认') {
			$json['warn'] = '此' . self::title . '已确认，不能修改';
		} else {
			$this->startTrans();
			$isPass = true;//事务通过标志
			if (!$info['id']) {
				$userNo       = codeTemplateClass::generateCode(self::page, [
					'prefix' => 'ZGTZ' . date('Ymd', strtotime($field['recordDate'])),
					'table'  => self::table,
					'field'  => 'orderNo',
					'where'  => " and coid = '" . self::$coid . "'",
				], $field);
				$field        = array_merge($field, [
					'id'      => $id,
					'orderNo' => $userNo,
					'state'   => '草稿',
					'coid'    => self::$coid,
					'stid'    => $this->control['stid'],
				]);
				$json['warn'] = static::insert(["table" => self::table, "field" => $field]);
			} else {
				$json['warn'] = static::update([
					"table" => self::table,
					"field" => $field,
					"where" => $where,
				]);
			}

			//添加或更新明细
			if (is_array($mxIdArr)) {
				foreach ($mxIdArr as $k => $nid) {
					$mx          = query(self::tableMx, "id = '$nid'");
					$targetInfo  = query('purchase_get_order_detail', "id = '$sourceIdArr[$k]'");
					$tableName   = 'purchase_get_order_detail';
					//数据格式处理
					$taxRateArr[$k] = floatval($taxRateArr[$k]) / 100;//税率从百分比转为小数
					$priceArr[$k]   = self::formattingFigure($priceArr[$k], 'pricePrecision');
					$result         = saleOrderClass::isTax($targetInfo['num'], $priceArr[$k], $taxRateArr[$k], $field['isTax']);
					if (!empty($mx['id'])) {
						//更新
						$warn = static::update([
							"table" => self::tableMx,
							"field" => [
								'sourceId'        => $sourceIdArr[$k],
								'sourceTable'     => $tableName,
								'materialId'      => $materialIdArr[$k],
								'price'           => $priceArr[$k],
								'taxMoney'        => $result['taxMoney'],//税额
								'moneyWithOutTax' => $result['money'],//不含税金额
								'money'           => $result['moneyWithTax'],//价税合计
								'rate'            => $taxRateArr[$k],
								'num'             => $targetInfo['num'],
							],
							"where" => " id = '$nid'",
						]);
					} else {
						//新增
						$warn = static::insert([
							"table" => self::tableMx,
							"field" => [
								'id'              => $nid,
								'orderId'         => $id,
								'coid'            => self::$coid,
								'sourceId'        => $sourceIdArr[$k],
								'sourceTable'     => $tableName,
                                'materialId'      => $materialIdArr[$k],
								'price'           => $priceArr[$k],
								'taxMoney'        => $result['taxMoney'],//税额
								'moneyWithOutTax' => $result['money'],//不含税金额
								'money'           => $result['moneyWithTax'],//价税合计
								'rate'            => $taxRateArr[$k],
								'num'             => $targetInfo['num'],
							],
						]);
					}
					if (!in_array($warn, ['新增成功', '更新成功'])) {
						$json['warn'] = $warn;
						break;
					}
				}
			}
			//添加主表ID到附件表
			if (is_array($fileIdArr)) {
				$warn = update(array(
				    'table' => 'file',
                    'field' => ['targetId' => $id],
                    'where' => " targetId = '' and id in ('" . implode("','", $fileIdArr) . "')"
                ));
				if ($warn != '更新成功') {
					$json['warn'] = $warn;
					$isPass       = false;
				}
			}
			if (in_array($json['warn'], ["新增成功", "更新成功"]) && $isPass) {
				$this->commitTrans();
				delete(array('table' => self::tableMx, 'where' => " id not in ('" . implode("','", $mxIdArr) . "') and orderId = '$id'"));
                if ($json['warn'] == '新增成功') {
                    self::insertOperateLog($id,self::title,"新建");
                }
				//添加日志
				$type = mb_substr($json['warn'], 0, 2, 'utf-8');
				$text = $this->control['name'] . $type . "了" . self::title . " id：【" . $id . '】';
				$this->logText(["type" => self::page, "text" => $text]);
				//返回
				$_SESSION['warn'] = $json['warn'];
				$json['warn']     = 2;
				$json['href']     = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&id=" . $id;
			} else {
				$this->rollback();
			}
		}
		resp:
		return json_encode($json, 320);
	}


	/**
	 * 关联采购收货单
	 *
	 * @return bool|string
	 */
	public function addSendOrder(): bool|string
	{
	    if(empty($this->post('supplierId'))){
	        return json_encode(['warn'=>'请选择供应商'], 320);
        }
        $layerId          = $this->get('cla') . ucwords($this->get('fun'));
		$html   =
			text(array("name" => "orderNo", "title" => "采购收货单号")) .
			text(array("name" => "recordDate", 'class' => 'width200', 'laydate' => ['type' => 'date', 'range' => '~'], "title" => "单据日期")) .
			text(array("name" => "code", "title" => "产品编码")) .
            text(array("name" => "materialName", "title" => "产品名称")) .
            text(array("name" => "model", "title" => "规格型号")) .
			hidden(array('name' => 'supplierId', 'value' => $this->post('supplierId'))) .
			hidden(array('name' => 'id', 'value' => $this->post('id'))) .
			hidden(array('name' => 'isTax', 'value' => $this->post('isTax'))) .
			hidden(array('name' => 'sourceId', 'value' => $this->post('sourceId') ? implode(',', $this->post('sourceId')) : ''));
		$button = "<input onclick=\"addRow();$('#" . $layerId . "').remove()\" type='button' class='searchSub m-l-5' value='提交'>";
		$html   = $this->search($html);
		return $this->layer(array("title" => "添加", "height" => 600, "width" => 1000, "html" => $html, "button" => $button));
	}

	/**
	 * 关联采购收货单
	 *
	 * @return bool|string
	 */
	public function addSendOrderSearch(): bool|string
	{
		$id         = $this->post('id');
		$supplierId = $this->post('supplierId');
		$sourceId   = $this->post('sourceId') ? explode(',', $this->post('sourceId')) : [];
        $result = find(array(
            'field' => "sourceId",
            'table' => self::tableMx." where orderId in (select id from purchase_esti_order where coid = '".self::$coid."' and supplierId = '$supplierId' and id <> '$id') "
        ));
        $bind = $result['array']?array_column($result['array'],'sourceId'):[];
        $sourceId = array_merge($sourceId,$bind);
		$where      = " 
		pgo.coid='" . self::$coid . "' 
		and pgo.supplierId = '$supplierId' 
		and mx.id not in ('" . implode("','", $sourceId) . "')";
		$and        = '';
		$like       = [
			'pgo.orderNo' => $this->post('orderNo'),
			'mat.code'    => $this->post('code'),
			'mat.name'    => $this->post('materialName'),
			'mat.model'   => $this->post('model'),
		];
		$equal      = [
			'pgo.state'      => '已确认',
			'pgo.estimation' => 1,
		];
		if ($this->post('recordDate')) {
			//单据日期
			$and .= self::timeComparison($this->post('recordDate'), 'date', 'pgo.recordDate');
		}
		$where .= search(["like" => $like, "=" => $equal]) . $and;
		$page  = $this->page([
			"table"   => " purchase_get_order_detail as mx join purchase_get_order as pgo on mx.orderId = pgo.id join material as mat on mx.materialId = mat.id ",
			"field"   => "mx.id,pgo.recordDate,pgo.orderNo,mat.code,mat.name,mat.model",
			"where"   => $where,
			'pageNum' => 50,
			"order"   => "pgo.recordDate desc,pgo.`orderNo` asc",
		]);
		//获取表头
		$checkAll = $this->checkAll("saleSendOrderForm", "saleSendOrderDetailId");
		$tr[]     = [$checkAll, '采购收货单号', '单据日期', '物料编码', '物料名称', '规格型号'];
		//获取记录
		foreach ($page['array'] as $array) {
			$dominate = array(
				"box" => array("name" => "saleSendOrderDetailId", "value" => $array['id']),
			);
			$tr[]     = array(
				$this->dominate($dominate),
				$array['orderNo'],
				$array['recordDate'],
				$array['code'],
				$array['name'],
				$array['model'],
			);
		}
		$json['html'] = $page['hint'] .
            "<form name='saleSendOrderForm'>" .
                hidden(array('name' => 'isTax', 'value' => $this->post('isTax'))) .
                hidden(array('name' => 'id', 'value' => $this->post('id'))) .
                $this->tableMany(array("tr" => $tr, "showSort" => true, "page" => $page['para'])) .
            "</form>" .
            $page['button'];
		return json_encode($json, 320);
	}

	/**
	 * 关联采购收货单
	 */
	public function addSendOrderEdit(): bool|string
	{
		$mxIdArr = $this->post('saleSendOrderDetailId');
		if (!$this->power(self::page, 'edit')) {
			$json['warn'] = '你还没有编辑权限';
		} elseif (empty($mxIdArr) || !is_array($mxIdArr)) {
			$json['warn'] = '请选择采购收货单';
		} else {
			$tr = [];
			foreach ($mxIdArr as $mxId) {
				$purchaseGetOrderMx = find(array(
				    'table' => "purchase_get_order as a join purchase_get_order_detail as b on a.id = b.orderId",
                    'single' => " b.id = '$mxId' order by list asc",
                    'field' => "b.*,a.orderNo"
                ));
				$material           = query('material', "id = '$purchaseGetOrderMx[materialId]'");
				$select             = select(array(
				    'name' => 'rate[]',
                    'change' => 'countMoney',
                    'value' => '',
                    'title' => '税率',
                    'option' => explode('，', para('taxRate'))
                ));
				$suiji              = self::getId();
				$rate               = ($purchaseGetOrderMx['rate'] * 100) . '%';
                $purchaseGetOrderMx['num']     = self::lostZero($purchaseGetOrderMx['num'],'numPrecision');
                $tr[] = [
                    componentClass::tablePperation('',"delTableRow(this);calculateTotal()").
                    hidden(array('name' => 'mxId[]', 'value' => $suiji)) .
                    hidden(array('name' => 'materialId[]', 'value' => $purchaseGetOrderMx['materialId'])) .
                    hidden(array('name' => 'sourceId[]', 'value' => $purchaseGetOrderMx['id'])) .
                    "<span class='pre_money hidden'>{$purchaseGetOrderMx['moneyWithOutTax']}</span>" .
                    "<span class='pre_tax_money hidden'>{$purchaseGetOrderMx['taxMoney']}</span>" .
                    "<span class='pre_money_with_tax hidden'>{$purchaseGetOrderMx['money']}</span>",
                    $material['code'],
                    $material['name'],
                    $material['model'],
                    $purchaseGetOrderMx['unit'],
                    "<span class='num'>" . self::lostZero($purchaseGetOrderMx['num'], 'numPrecision') . "</span>",
                    $purchaseGetOrderMx['price'],
                    $rate,
                    text(array('name' => 'price[]', 'other' => self::digitalFiltering('pricePrecision'), 'blur' => 'countMoney', 'value' => '')),
                    $select,
                    "<span class='rowMoney'></span>",
                    "<span class='taxMoney'></span>",
                    "<span class='moneyWithTax'></span>",
                    "<span class='diff_money'></span>",
                    "<span class='diff_tax_money'></span>",
                    "<span class='diff_money_with_tax'></span>",
                    $purchaseGetOrderMx['orderNo'] ?? '',
                ];
			}
			$json['warn'] = 2;
            $json['html'] = $this->tableMany(['tr' => $tr, 'thead' => false]);
		}
		return json_encode($json, 320);
	}


	/*详情页*/
	public function detail(): string
	{
		$info = query(self::table, " id = '{$this->get('id')}'");
		if (empty($info['id'])) {
			$html = '未找到此' . self::title;
		} else {
			//菜单
			$data = array(
				"id" => $info['id'],
			);

			$button = [];
			if ($info['state'] == '草稿') {
				if ($this->power(self::page, "edit")) {
                    //按钮
                    $button[] = [
                        "name"  => "提交",
                        "type"  => "弹出层",
                        "cla"   => $this->get('cla'),
                        "fun"   => "operate",
                        "post"  => ["act" => 'commit', "id" => $info['id']],
                        'style' => 'li-btn-blue-bg',
                    ];
					//按钮
					$button[] = [
						"name"  => "编辑",
						"type"  => "顶部页卡",
						"title" => self::title . "详情",
						"url"   => $this->root . "control/adIndex.html?cla={$this->get('cla')}&fun=edit&id=" . $info['id'],

					];
				}
				if ($this->power(self::page, "del")) {
					//按钮
					$button[] = [
						"name" => "删除",
						"type" => "弹出层",
						"cla"  => $this->get('cla'),
						"fun"  => "operate",
						"post" => ["act" => 'del', "id" => $info['id']],
					];
				}
			}
            //按钮
			$button[] = [
				"name" => "打印",
				"type" => "点击事件",
				"fun"  => "window.open('" . root . "control/adIndex.html?cla=" . self::page . "&fun=printPage&id={$info['id']}')",
			];
			if ($this->power(self::page, "confirm") && $info['state'] == '待确认') {
				$button[] = [
					"name"  => "复核",
					"type"  => "弹出层",
					"cla"   => $this->get('cla'),
					"fun"   => "operate",
					"post"  => ["act" => 'confirm', "id" => $info['id']],
					'style' => 'li-btn-blue-bg',
				];
			}
			if ($this->power(self::page, "confirm") && $info['state'] != '草稿') {
				$button[] = [
					"name" => "撤销",
					"type" => "弹出层",
					"cla"  => $this->get('cla'),
					"fun"  => "operate",
					"post" => ["act" => 'cancel', "id" => $info['id']],
				];
			}
			//操作记录
            $button[] = self::operateLogBut($info['id'],1);

			$isTax  = $info['isTax'] ? '含税' : '不含税';
			$tr[]   = ['物料编码', '物料名称', '规格型号', '单位', '数量', '原单价(' . static::$unit . ')', '原税率%', '调整后' . $isTax . '单价（' . static::$unit . '）', '调整后税率%', '调整后未税金额（' . static::$unit . '）', '调整后税额（' . static::$unit . '）', '调整后价税合计（' . static::$unit . '）', '未税金额差额（' . static::$unit . '）', '税额差额（' . static::$unit . '）', '价税合计差额（' . static::$unit . '）', '关联采购收货单'];
			$result = find(array('table' => self::tableMx, 'where' => "orderId = '$info[id]' order by list"));
			foreach ($result['array'] as $array) {
				$material                    = query('material', " id = '$array[materialId]'");
				$targetMx                    = query("purchase_get_order_detail", "id = '$array[sourceId]'");
				$target                      = query('purchase_get_order', "id = '$targetMx[orderId]'");
				$targetMx['money']           = $targetMx['money'] ?: 0;
				$targetMx['taxMoney']        = $targetMx['taxMoney'] ?: 0;
				$targetMx['moneyWithOutTax'] = $targetMx['moneyWithOutTax'] ?: 0;
				$diffMoney                   = self::formattingFigure($array['moneyWithOutTax'] - $targetMx['moneyWithOutTax']);
				$diffTaxMoney                = self::formattingFigure($array['taxMoney'] - $targetMx['taxMoney']);
				$diffMoneyWithTax            = self::formattingFigure($array['money'] - $targetMx['money']);

				$tr[] = [
					$material['code'],
					$material['name'],
					$material['model'],
					$targetMx['unit'],
					self::lostZero($array['num'], 'numPrecision'),
					self::lostZero($targetMx['price'], 'pricePrecision'),
					($targetMx['rate'] * 100) . '%',
					self::lostZero($array['price'], 'pricePrecision'),
					($array['rate'] * 100) . '%',
					self::lostZero($array['moneyWithOutTax']),
					self::lostZero($array['taxMoney']),
					self::lostZero($array['money']),
					$diffMoney,
					$diffTaxMoney,
					$diffMoneyWithTax,
					$target['orderNo'] ?? '',
				];
			}
			$total                 = find(array(
			    'table' => self::tableMx,
                'field' => "
                ifnull(sum(num),0) as num,
                ifnull(sum(money),0) as totalMoney,
                ifnull(sum(taxMoney),0) as taxMoney,
                ifnull(sum(moneyWithOutTax),0) as money",
                'single' => "orderId = '$info[id]'"
            ));
			$preTotal              = find(array(
			    'table' => 'purchase_get_order_detail',
                'field' => "
                ifnull(sum(money),0) as totalMoney,
                ifnull(sum(taxMoney),0) as taxMoney,
                ifnull(sum(moneyWithOutTax),0) as money",
                'single' => " id in (select sourceId from " . self::tableMx . " where orderId = '$info[id]') "
            ));
			$total['num']   = $total['num'] ?? 0;
			$total['totalMoney']   = $total['totalMoney'] ?? 0;
			$total['taxMoney']     = $total['taxMoney'] ?? 0;
			$total['money']        = $total['money'] ?? 0;
			$totalDiffMoney        = self::formattingFigure($total['money'] - $preTotal['money']);
			$totalDiffTaxMoney     = self::formattingFigure($total['taxMoney'] - $preTotal['taxMoney']);
			$totalDiffMoneyWithTax = self::formattingFigure($total['totalMoney'] - $preTotal['totalMoney']);
            $total_tr = [
                    4=>self::lostZero($total['num'],'numPrecision'),
                    9=>self::lostZero($total['money']),
                    10=>self::lostZero($total['taxMoney']),
                    11=>self::lostZero($total['totalMoney']),
                    12=>$totalDiffMoney,
                    13=>$totalDiffTaxMoney,
                    14=>$totalDiffMoneyWithTax
            ];
			//生成表单
            $data['button'] = $this->tableShowButton($button);
			$data['html'] = $this->tableShow(array(
				'详细信息' => array(
					array(
						"供应商"   => supplierClass::getName($info['supplierId']),
						"单据日期" => self::null($info['recordDate']),
                        "单据编号" => $info['orderNo'],
                        "制单人"   => self::findStaff($info['stid']),
					),
					array(
						"状态"     => $info['state']
					),
                    array(
                        "备注"     => pre($info['text']),
					),
				),
			));
            $data['html'] .= $this->detailList([
                'title' => '明细',
                'html' => $this->listTable(array('tr' => $tr, 'showEmpty' => true, 'total' => $total_tr, 'showSort' => true)),
            ]);
            $data['html'] .= $this->detailBlock([
                '附件' => fileUploadClass::showFile($info['id'], '暂估调整单')
            ]);
			//生成页面
			$html = $this->tab($data);
		}
		//返回
		return $html;
	}

	/**
	 * 确认
	 */
	public function confirmEdit()
	{
		$id    = $this->post('id');
		$info  = query(self::table, " id = '$id'");
		$field = [
			'state'       => '已确认',
			'checkId'     => self::$stid,
			'confirmTime' => $this->time,
		];

		if (!$this->power(self::page, 'confirm')) {
			$json['warn'] = '你还没有确认权限';
		} elseif (empty($info['id'])) {
			$json['warn'] = '未找到此暂估调整单';
		} elseif ($info['state'] != '待确认') {
			$json['warn'] = '此退货单不是待确认状态，不能确认';
		} else {
			$this->startTrans();
			$json['warn'] = update(array(
				"table" => self::table,
				"field" => $field,
				"where" => "id = '$info[id]'",
			));
			$bool         = $this->adjustMoney($info);
			if ($bool !== true) {
				$json['warn'] = $bool;
			}
			if (in_array($json['warn'], ["新增成功", "更新成功"])) {
				$this->commitTrans();
                // 单据是否需要复核
                if(!in_array(self::page,self::$publicSettings['documentReview'])) {
                    self::insertOperateLog($info['id'],self::title,"提交、复核");
                }else{
                    self::insertOperateLog($info['id'],self::title,"复核");
                }
				//添加日志
				$type = mb_substr($json['warn'], 0, 2, 'utf-8');
				$text = $this->control['name'] . $type . "了" . self::title . "id：【" . $id . '】';
				$this->logText(["type" => self::page, "text" => $text]);
				//返回
				$_SESSION['warn'] = $json['warn'];
				$json['warn']     = 2;
				$json['href']     = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&id=" . $info['id'];
			} else {
				$this->rollback();
			}
		}
		resp:
		return json_encode($json, 320);
	}


	/**
	 * 撤销
	 */
	public function cancelEdit()
	{
		$id    = $this->post('id');
		$info  = query(self::table, " id = '$id'");
		$field = [
			'state'       => '草稿',
			'checkId'     => '',
			'confirmTime' => '',
		];
		$warn  = '';
		$all   = find(array('table' => self::tableMx, 'where' => "orderId = '$info[id]' order by list"));
		foreach ($all['array'] as $array) {
			$record = query('record', "typeId = '$info[supplierId]' and coid = '" . self::$coid . "' and sourceId = '$array[id]'");
			if ($record['id'] && static::total(array('table' => 'record', 'where' => "typeId = '$info[supplierId]' and coid = '" . self::$coid . "' and id > '$record[id]'")) > 0) {
				$supplier = query('supplier', "id = '$info[supplierId]'");
				$warn     = "供应商【{$supplier['name']}】已生成了后续应付款记录，不能撤销";
			}
		}
		if (!$this->power(self::page, 'cancel')) {
			$json['warn'] = '你还没有撤销权限';
		} elseif (empty($info['id'])) {
			$json['warn'] = '未找到此暂估调整单';
		} elseif ($info['state'] != '已确认') {
			$json['warn'] = '此调整单不是已确认状态，无需撤销';
		} elseif ($warn) {
			$json['warn'] = $warn;
		} else {
			$json['warn'] = update(array(
				"table" => self::table,
				"field" => $field,
				"where" => "id = '$info[id]'",
			));
			if (in_array($json['warn'], ["新增成功", "更新成功"])) {
				$all = find(array('table' => self::tableMx, 'where' => "orderId = '$info[id]' order by list"));
				foreach ($all['array'] as $array) {
					$record = query('record', "typeId = '$info[supplierId]' and coid = '" . self::$coid . "' and sourceId = '$array[id]'");
					delete(array('table' => 'record', 'where' => "id = '$record[id]'"));
				}
                self::insertOperateLog($info['id'],self::title,"撤销");
				//添加日志
				$type = mb_substr($json['warn'], 0, 2, 'utf-8');
				$text = $this->control['name'] . $type . "了" . self::title . "id：【" . $id . '】';
				$this->logText(["type" => self::page, "text" => $text]);
				//返回
				$_SESSION['warn'] = $json['warn'];
				$json['warn']     = 2;
				$json['href']     = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&id=" . $info['id'];
			}
		}
		resp:
		return json_encode($json, 320);
	}
    /**
     * Desc : 提交前数据验证
     * User : you name
     * Date : 2023-11-17 16:04
     * @param $info
     * @return string|bool
     */
    public function dataValidation($info): string|bool
    {
        $annotation       = [
            'supplierId' => '供应商',
            'recordDate' => '单据日期',
        ];
        $rules            = [
            'supplierId' => 'required',
            'recordDate' => 'required|date',
        ];
        // 校验是否符合规则
        $vt     = new \verify();
        $result = $vt->setAliases($annotation)->validate($info, $rules)->isOk();
        if ($result === false) {
            return $vt->getErrs()[0];  // 多个规则提示最前面一条
        }
        $result = find(array('table' => self::tableMx, 'field' => 'id,materialId,price', 'where' => "orderId = '$info[id]' order by list"));
        if(count($result['array']) == 0){
            return "请完善退货明细";
        }
        if(static::is_null_array(array_column($result['array'],'materialId'))){
            return "退货明细中【属性】不能为空";
        }
        if(static::is_null_array(array_column($result['array'],'price'))){
            return "退货明细中【单价】不能为空";
        }

        return true;
    }
	/**
	 * 提交
	 */
	public function commitEdit()
	{
		$id    = $this->post('id');
		$info  = query(self::table, " id = '$id'");
		$field = [
			'state' => '待确认',
		];
        //提交前数据验证
        $json['warn'] = $this->dataValidation($info);
        if($json['warn'] !== true){
            goto resp;
        }
		if (!$this->power(self::page, 'edit')) {
			$json['warn'] = '你还没有编辑权限';
		} elseif (empty($info['id'])) {
			$json['warn'] = '未找到此暂估调整单';
		} elseif ($info['state'] != '草稿') {
			$json['warn'] = '此暂估调整单不是草稿状态，不能提交';
		} else {
            $this->startTrans();
			$json['warn'] = update(array(
				"table" => self::table,
				"field" => $field,
				"where" => "id = '$info[id]'",
			));
			if (in_array($json['warn'], ["新增成功", "更新成功"])) {
                // 单据是否需要复核
                if(!in_array(self::page,self::$publicSettings['documentReview'])){
                    $resultJson = $this->confirmEdit();
                    $json = json_decode($resultJson,true);
                    if ($json['warn'] != 2){
                        $this->rollback();
                        goto resp;
                    }
                }else {
                    self::insertOperateLog($info['id'],self::title,"提交");
                }
                $this->commitTrans();
				//添加日志
				$type = mb_substr($json['warn'], 0, 2, 'utf-8');
				$text = $this->control['name'] . $type . "了" . self::title . "id：【" . $id . '】';
				$this->logText(["type" => self::page, "text" => $text]);
				//返回
				$_SESSION['warn'] = $json['warn'];
				$json['warn']     = 2;
				$json['href']     = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&id=" . $info['id'];
			} else {
                $this->rollback();
            }
		}
		resp:
		return json_encode($json, 320);
	}

	private function adjustMoney($info): bool|string
	{
		$all = find(array('table' => self::tableMx, 'where' => "orderId = '$info[id]' order by list"));
		foreach ($all['array'] as $array) {
			$inventoryDetail = find(array('table' => 'inventory_detail', 'where' => "sourceId = '$array[sourceId]' and sourceTable = 'purchase_get_order_detail'"));
			foreach ($inventoryDetail['array'] as $val) {
				$inventory = query('inventory', " id = '$val[orderId]' ");
				if ($info['isTax']) {
					$price = self::formattingFigure($array['price'] - $val['price'] * (1 + $val['rate']), 'pricePrecision');
				} else {
					$price = self::formattingFigure((1 + $array['rate']) * $array['price'] - $val['price'] * (1 + $val['rate']), 'pricePrecision');
				}
				$targetDate  = $info['recordDate'];
				$targetNo    = $info['orderNo'];
				$targetText  = "暂估调整单【{$info['orderNo']}】";
				$hiddenText  = '暂估调整单ID：' . $info['id'] . '，明细ID：' . $array['id'];
				$money       = self::formattingFigure($val['num'] * $price);
				$material    = query('material', "id = '$val[materialId]'");
				$warn        = static::insert(array(
					'table' => 'record',
					'field' => array(
						'coid'          => self::$coid,
						'typeId'        => $inventory['targetId'],
						'type'          => '供应商',
						'direction'     => '-',
						'money'         => -$money,
						'classify'      => '暂估调整单',
						'balance'       => supplierClass::money($inventory['targetId']) - $money,
						'text'          => $targetText,
						'orderNo'       => $targetNo,
						'sourceTable'   => self::tableMx,
						'sourceId'      => $array['id'],
						'materialId'    => $material['id'] ?? '',
						'num'           => $val['num'],
						'price'         => $price,
						'unit'          => $val['unit'],
						'targetDate'    => $targetDate,
						'stName'        => self::$user['name'],
						'hiddenText'    => $hiddenText,
					),
				));
				if ($warn != '新增成功') {
					return '生成应付记录失败';
				}
			}
		}
		return true;
	}

	// 操作中转
	public function operate()
	{
		$act  = $this->post('act') ?? '';
		$pwd  = $word = false; // 需要密码
		$form = $power = '';
		switch ($act) {
			case 'confirm':
				$act      = 'confirm';
				$msg      = '确认';
				$title    = '是否已确认此暂估调整单，确认后将不可修改？';
				$function = 'confirmEdit';
				$form     = self::page . 'OperateForm, detailForm';
				$power    = '';
				$word     = true;
				break;
			case 'commit':
				$act      = 'edit';
				$msg      = '编辑';
				$title    = '是否确认提交此暂估调整单？';
				$function = 'commitEdit';
				$form     = self::page . 'OperateForm, detailForm';
				$power    = '';
				$word     = true;
				break;
			case 'cancel':
				$act      = 'cancel';
				$msg      = '撤销';
				$title    = '是否确认撤销此暂估调整单？';
				$function = 'cancelEdit';
				$form     = self::page . 'OperateForm, detailForm';
				$power    = '';
				$word     = true;
				break;
			default:
				$act      = 'del';
				$msg      = '删除' . self::title;
				$title    = self::page . 'Delete';
				$function = 'delete';
				$form     = self::page . 'OperateForm, listForm, quoForm';
				$power    = '';
				break;
		}
		if (!$this->power(self::page, $act)) {
			$_SESSION['warn'] = '你还没有' . $msg . '的权限';
			$json             = [
				'warn' => 2,
				'href' => root . 'control/adIndex.html?cla=' . $this->get('cla') . '&fun=home',
			];
		} else {
			return $this->confirm([
				'title'    => $title,
				'function' => $function,
				'form'     => $form,
				'power'    => $power,
				'pwd'      => $pwd,
				'word'     => $word,
			]);
		}

		resp:
		return json_encode($json, 320);
	}

	/**
	 * 删除
	 *
	 * @return bool|string
	 */
	public function delete()
	{
		$array = $this->post('listId') ?? $this->post('id');
		if (!$this->power(self::page, "del")) {
			$json['warn'] = "你没有删除的权限";
		} elseif (empty($array)) {
			$json['warn'] = "你一个数据都没有选择呢";
		} else {
			$text  = "";
			$x     = 0;
			$array = is_array($array) ? $array : [$array];
			foreach ($array as $id) {
				$info = query(self::table, " id = '$id' ");
				if ($info['state'] == '已确认') {
					$warn = "删除失败：已确认，暂不能删除";
				} else {
					//最后删除基本参数
                    fileClass::deleteFile($id);
					delete(array("table" => self::table, "where" => " id = '$id' "));
					delete(array("table" => self::tableMx, "where" => " orderId = '$id' "));
					delete(array("table" => "auditing_follow", "where" => " typeId = '$id' "));
					//返回
					$warn = "删除成功";
					$x++;
				}
				$text .= self::title . "ID【" . $info['id'] . "】" . $warn . "。<br>";
			}
			//添加日志
			$text = $this->control['name'] . "删除了" . self::title . "，结果如下：<br>" . $text;
			$this->logText(array("type" => self::page, "text" => $text));
			$_SESSION['warn'] = "删除了" . $x . "个" . self::title . "，详情见系统日志。";
			$json['warn']     = 2;
			$json['href']     = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=home";
		}
		return json_encode($json, 320);
	}

	/**
	 * 批量打印
	 *
	 * @return string
	 */
	public function batchPrint(): string
	{
		$lists = $this->get('lists');
		if (empty($lists)) {
			exit('参数错误');
		} else {
			$listId = base64_decode($lists, true);
			$array  = explode(',', $listId);
			$data   = [];
			foreach ($array as $id) {
				$data[] = static::printPage($id, false);
			}
			return (new printTemplateClass())->start(self::page, $data);
		}
	}

	/**
	 * 打印
	 *
	 * @return string
	 */
	public function printPage($param = '', $isReturn = true): string|array
	{
		$id                    = $param ?: $this->get('id');
		$info                  = query(self::table, " id = '$id'");
		$info['companyName']   = query('company', "coid = '" . self::$coid . "'")['name']; //公司名称//公司名称
		$info['title']         = self::title;
		$info['printTime']     = $this->time;
		$info['stid']          = self::findStaff($info['stid']);
		$info['supplierName']  = query('supplier', "id = '$info[id]'")['name'];
		$info['qr']            = "source=" . self::table . "&id=" . $info['id'];
		$info['tags']          = orderTagClass::getTagName($info['id']);
		$detail                = find(['table' => self::tableMx, 'where' => "orderId = '$info[id]' order by list asc"])['array'];
		$items                 = [];
		$x                     = 1;
		$totalNum              = 0;
		$totalMoney            = 0;
		$diffTaxMoneyTotal     = 0;
		$diffMoneyWithTaxTotal = 0;
		foreach ($detail as $array) {
			$material              = query('material', "id = '$array[materialId]'");
			$targetMx              = query("purchase_get_order_detail", "id = '$array[sourceId]'");
			$diffTaxMoney          = $array['taxMoney'] - $targetMx['taxMoney'];
			$diffMoneyWithTax      = $array['money'] - $targetMx['money'];
			$diffTaxMoneyTotal     += $diffTaxMoney;
			$diffMoneyWithTaxTotal += $diffMoneyWithTax;
			$items[]               = [
				'no'              => $x,
				'materialCode'    => $material['code'],
				'materialName'    => $material['name'],
				'oldPrice'        => self::lostZero($targetMx['price'], 'pricePrecision'),
				'oldRate'         => ($targetMx['rate'] * 100) . '%',
				'price'           => self::lostZero($array['price'], 'pricePrecision'),
				'rate'            => ($array['rate'] * 100) . '%',
				'taxMoney'        => self::lostZero($array['taxMoney']),
				'moneyWithOutTax' => self::lostZero($array['moneyWithOutTax']),
				'money'           => self::lostZero($array['money']),
				'model'           => $material['model'],
				'unit'            => $targetMx['unit'],
				'num'             => $array['num'],
				'diffTaxMoney'    => self::lostZero($diffTaxMoney),
				'diffMoney'       => self::lostZero($diffMoneyWithTax),
			];
			$x++;
			$totalNum   += $array['num'];
			$totalMoney += $array['money'];
		}
		$append         = [
			'no'           => '合计',
			'num'          => self::lostZero($totalNum),
			'money'        => self::lostZero($totalMoney),
			'diffTaxMoney' => self::lostZero($diffTaxMoneyTotal),
			'diffMoney'    => self::lostZero($diffMoneyWithTaxTotal),
		];
		$items[]        = $append;
		$info['detail'] = $items;
		if ($isReturn) {
			return (new printTemplateClass())->start(self::page, $info);
		} else {
			return $info;
		}
	}
}

